<?php
    include __DIR__."/config/cors.php";
    include __DIR__."/database.php";
    session_start();

    $username = $_POST['username'];
    $password = $_POST['password'];
    $passwordtoo = $_POST['passwordtoo'];
    $role = $_POST['role'];
    $mail = $_POST['mail'];

    if(!isset($username) or !isset($password) or !isset($passwordtoo) or !isset($role) or !isset($mail)){
      echo json_encode([
          "code" => 204,
          "msg"=> "请填写完整信息"
        ]);
        exit;
    }

    $loginusername = @$_POST['loginusername'];
    $loginrole = @$_POST['loginrole'];

    if(!isset($loginusername) or !isset($loginrole)){
      echo json_encode([
          "code" => 202,
          "msg"=> "请管理员登陆后在添加"
        ]);
        exit;
    }

    if ($password != $passwordtoo) {
        echo json_encode([
            "code" => 203,
            "msg"=>"两次密码不一致"
        ]);
        exit;
    }
    $db = new DB();
    $sql = "select * from user where username = '$username'";
    $data = $db->selectOne($sql);
    if (is_array($data) and count($data) > 0) {
        echo json_encode([
            "code" => 201,
            "msg"=>"添加失败"
        ]);
    }else {
        if(is_array($data) and count($data) == 0){
            $sql = "insert into user (username,password,mail,register,role) values ('$username','$password','$mail',NOW(),'$role')";
            if ($db->insert($sql)) {
                echo json_encode([
                    "code" => 200,
                    "msg"=>"添加成功"
                ]);
            } else {
                echo json_encode([
                    "code" => 204,
                    "msg"=> "添加失败: " . $data
                ]);
            }
        }else {
            echo json_encode([
                "code" => 204,
                "msg"=> "添加失败: " . $data
              ]);
        }
    }
?>